<?php
            
use app\model\Record; 
use app\model\Theme; 


/**
 * Desc:客户预约首页
 * Time: 2021/6/26 15:19 下午
 * author：wsx
 */
class Index_Page extends PluginMobilePage {
    //主页面（入口按钮文字，分店店铺信息）
    function main(){
        global $_P,$_G,$_S,$_C;
        $fromtype = $_P['from'];
        //基本检测
        $fans = $this->checkuser();
        $user['name']=$fans['username'];//用户名
        $user['mobile']=$fans['mobile'];//用户手机

        $themeid = isset($_P['themeid'])?$_P['themeid']:'';
        $theme = Theme::getThemeById($themeid);
        $fromuid = isset($_P['fromuid'])?$_P['fromuid']:'';

        if (!$themeid || !$theme) {
            return_json(1,'活动入口不正确');
        }

        //检查该活动id（店铺id），该用户uid时候有过预约
        $planedinfo = ShopplanModel::getUserPlanByUid($fans['uid'],$themeid);
        $planedid = $_P['planedid'];//预约的流水id
        if(isset($planedid)){
            $planedinfo = false;
        }
        //预约过的客户，返回原来的预约信息
        if ($planedinfo) {
            $storeid = $planedinfo['storeid'];
            $shopid  = $planedinfo['shopid'];

            //开始获取店铺-分店配置信息
            if ($storeid) {
                $item = ShopplanModel::getConfigByStoreId($storeid);
                $agelimit = $item['agelimit'];//门店年龄限制开关，0为关闭，1为开启
            }

            //查找分店信息
            if (!empty($item['shopconfig'])) {
                $shopconfig=json_decode($item['shopconfig'],TRUE);
                foreach ($shopconfig as $key => $value) {
                    if ($value['shopid'] ==$shopid) {
                        $shop['name'] = $value['name'];
                        $shop['address']  = $value['address'];
                        $shop['phone']  = $value['phone'];
                    }
                }
            }

            $planedinfo['plan_at']=substr($planedinfo['plan_at'],0,-3);
            $date=substr($planedinfo['plan_at'],0,-6);  //注意：是在上一行截取了-3的基础上，又截取了-6

            if ($planedinfo['birthday']=='0000-00-00 00:00:00') {
                $birthday = '' ;
            } else {
                $birthday = date('Y-m-d',strtotime($planedinfo['birthday']));
            }
            
            $planedid = $planedinfo['id'];

            //获取条件，判断是否可以客户自助修改
            //条件1：预约之后,最长多少天内可以修改,默认7天，$item['enable_days']
            //条件2：距离预约的日期,最晚多少天之外可以修改,默认3天，$item['days_away']
            //条件3：客户最多可修改的次数,默认5次，$item['max_edit_nums']

            $self_edit = false;
            if ((strtotime($planedinfo['created_at'])+$item['enable_days']*86400 >= time()) && (strtotime($planedinfo['plan_at'])-$item['days_away']*86400 >= time()) && $planedinfo['edit_nums'] < $item['max_edit_nums']) {
                $self_edit = true;
            }

            /*返回数据：*/
            $planed['shopname']=$shop['name'];
            $planed['shopaddress']=$shop['address'];
            $planed['shopphone']=$shop['phone'];
            $planed['username']=$user['name'];
            $planed['usermobile']=$user['mobile'];
            $planed['plan_at']=$planedinfo['plan_at'];
            $plan_config['themeid']=$themeid;
            $plan_config['date']=$date;
            $plan_config['birthday']=$birthday;
            $plan_config['planedid']=$planedid;

            if ($fromtype=='mobile') {
                $ruleBtn_html='您的预约店铺是'.$shop['name'].'（'.$shop['address'].'）,<br>预约时间是'.$planedinfo['plan_at'];
                $plan_status_html = $item['planedtext'];

                $format_res = [
                    'ruleBtn_html'=>Theme::encode($ruleBtn_html),
                    'plan_status' => Theme::encode($plan_status_html),
                ];
                return_json(0,'操作成功',$format_res);
            } elseif ($fromtype=='wxapp') {
                $format_res = [
                    'plan_status'=>$item['planedtext'],
                    'planedinfo' =>$planed,
                    'plan_config'=>$plan_config,
                    'self_edit'  =>$self_edit,
                    'agelimit'   =>(int)$agelimit,
                    'theme'   =>$theme,
                ];
                return_json(0,"您的预约店铺是\n".$shop['name']."（".$shop['address']."）,\n预约时间是".$planedinfo['plan_at'],$format_res);
            }
        }

        //判断用户是否存在订单
        $themyrecord = Record::getLastGroupByUid($fans['uid'],$themeid);
        $themyrecord = true;//模拟支付成功

        if ($themyrecord) {

            $storeid = isset($_P['storeid'])?$_P['storeid']:$themeid;
            $shopid = isset($_P['shopid'])?$_P['shopid']:'1';  //获取分店shopid
            //开始获取店铺-分店配置信息
            if ($storeid) {
                $item = ShopplanModel::getConfigByStoreId($storeid);
                $agelimit = $item['agelimit'];//门店年龄限制开关，0为关闭，1为开启
            }

            if ($fromtype=='mobile') {

                //查找分店信息
                if (!empty($item['shopconfig'])) {
                    $shopconfig = json_decode($item['shopconfig'], TRUE);

                } else {
                    return_json(1, '管理员还没有配置好店铺信息');
                }

                $plan_status_html = $item['plantext'];

                $format_res = [
                    'plan_status' => Theme::encode($plan_status_html),
                ];
                return_json(0, '操作成功', $format_res);

                $return_client = get_defined_vars();
        return $this->view("shopplan/index", $return_client);
                return; //退出程序执行

            }elseif ($fromtype=='wxapp') {
                $temp_shop_config_list_arr = [];
                //查找分店信息
                if (!empty($item['shopconfig'])) {
                    $shopconfig=json_decode($item['shopconfig'],TRUE);
                    foreach ($shopconfig as $key => $value) {
                        $temp_str = $value['name'].'-'.$value['address'];
                        array_push($temp_shop_config_list_arr,$temp_str);
                    }

                }else{
                    return_json(1,'管理员还没有配置好店铺信息');
                }

                $format_res = [
                    'shopconfig'=>$shopconfig,
                    'show_shop_list'=>$temp_shop_config_list_arr,
                    'plan_status'=>$item['plantext'],
                    'planedid'=>$planedid,
                    'agelimit'   =>(int)$agelimit,
                    'theme'   =>$theme,
                ];
                return_json(0,'操作成功',$format_res);

            }


        }else {
            return_json(1, '支付后才能预约！', []);

            if ($fromtype == 'mobile') {
                $return_client = get_defined_vars();
        return $this->view("shopplan/index", $return_client);
                return; //退出程序执行
            }
        }
    }
    //客户预约表（返回前端数据填写的form）
    function userplan(){
        global $_P,$_G,$_S,$_C;
        $fromtype = $_P['from'];

        if (!$_G['ispost']) {
            return_json(1,'发生了意外');
        } else {
            $themeid = isset($_P['themeid'])?$_P['themeid']:'';
            $theme = Theme::getThemeById($themeid);
            $fromuid = isset($_P['fromuid'])?$_P['fromuid']:'';
            if (!$themeid || !$theme) {
                return_json(1,'活动入口不正确');
            } else {
                $fans = $this->checkuser();
                if ($fans && $fans['uid']){

                    //接受并处理前端传值信息
                    $shopid = isset($_P['shopid'])?$_P['shopid']:'1';
                    $storeid = isset($_P['themeid'])?$_P['themeid']:$_P['storeid'];
                    $date=$_P['date'];//获取前端页面点击“日期”后的传值
                    $totalnums=$_P['totalnums'];//传值日期的可预约客户总数
                    $planed=$_P['planed'];//传值日期的已经预约数
                    $tplid=$_P['tplid'];//传值日期的时间规划值
                    $birthday=$_P['birthday'];//用户宝贝的生日

                    //根据宝宝生日，计算宝宝当前月龄
                    $age = strtotime($birthday); 
                    $now = time(); 
                    $age =floor(($now-$age)/86400/30);

                    //如果有（商家id+店铺id），获取配置信息
                    if ($storeid && $shopid >= 1) {
                        $item2 = ShopplanModel::getTimeConfigByStoreId($storeid,$shopid);
                    }

                    //规划规则
                    $item3 = ShopplanModel::getSpecialWorktimesById($tplid);
                    $work_rules=json_decode($item3['s_work_rules'],TRUE);

                    //获取已经预约的（时间段+数量）
                    $get_item = ShopplanModel::searchUserPlaned4($themeid,$shopid,$date);
                    sort($get_item);


                    foreach ($work_rules as $k => $v) {
                        foreach ($get_item as $key1 => $value1) {
                            if ($v['worktimes']==substr($value1['p_date'],-5)) {
                                if ($work_rules[$k]['nums']>=$value1['nums']) {
                                    $work_rules[$k]['p_nums']=$value1['nums'];
                                }else{
                                    return_json(1,'本时间段预约人数超标！');//报错，提示本时间段预约满员
                                }
                            }
                        }
                    }
                    $worktimes_list_arr = [];
                    foreach ($work_rules as $key => $value) {
                        $value['p_nums']=!empty($value['p_nums'])?$value['p_nums']:'0';
                        if ($value['p_nums'] < $value['nums'] && $item3['agelimit']==1 && $value['ages_start'] <= $age && $age <= $value['ages_end']) {
                            array_push($worktimes_list_arr,$value['worktimes']);
                        }elseif ($value['p_nums'] < $value['nums'] && $item3['agelimit']==0){
                            array_push($worktimes_list_arr,$value['worktimes']);
                        }
                        //如果是今天，时间段小于等于2小时之内的，去除
                        $arr=[];
                        if ($date==date("Y-m-d")){
                            $time=$date.' '.$value['worktimes'].':00';
                            if (strtotime($time) - time() <= 0){
                                array_push($arr,$value['worktimes']);
                                $worktimes_list_arr = array_merge(array_diff($worktimes_list_arr, $arr));

                            }
                        }

                    }

                    //前端可以使用$work_rules数据
                    
                    if ($fromtype=='mobile') {

                        //拼接一个前端数据填写表
                        $ruleBtn_html="<form id=\"form_plan\" enctype =\"multipart/form-data\" method=\"post\">".PHP_EOL;
                        $ruleBtn_html.="<table width='90%' border='0px' style='text-align:left; margin-left:20px;'>".PHP_EOL;
                        
                        $ruleBtn_html.="<tr>".PHP_EOL;
                        $ruleBtn_html.="<th style='height: 40px;'>预约日期：<input type=\"text\" name=\"date\" value=\"{$date}\" readonly=\"readonly\"/></th>".PHP_EOL;
                        $ruleBtn_html.="<tr>".PHP_EOL;

                        $ruleBtn_html.="<tr>".PHP_EOL;
                        $ruleBtn_html.="<th style='height: 40px;'>预约时间：".PHP_EOL;
                        $ruleBtn_html.="<select name=\"time\">".PHP_EOL;
                        $ruleBtn_html.="<option disabled selected>请选择时间</option>".PHP_EOL;
                        foreach ($worktimes_list_arr as $key => $value) {
                                $ruleBtn_html.="<option value=\"{$value}\">{$value}</option>".PHP_EOL;
                        }        
                        $ruleBtn_html.="</select>".PHP_EOL;
                        $ruleBtn_html.="<tr>".PHP_EOL;

                        $ruleBtn_html.="<tr style=\"display:none;\">".PHP_EOL;
                        $ruleBtn_html.="<th style='height: 40px;'>宝贝生日：";
                        $ruleBtn_html.="<input type=\"date\" name=\"birthday\" min=\"1921-01-01\" max=\"2030-12-31\" value=\"{$birthday}\" >";
                        $ruleBtn_html.="</th>".PHP_EOL;
                        $ruleBtn_html.="<tr>".PHP_EOL;

                        $ruleBtn_html.="<tr>".PHP_EOL;
                        $ruleBtn_html.="<th style='height: 40px;'>留言备注：<input type=\"text\" name=\"note\" value=\"请3天前提醒\" maxlength=\"30\" size=\"30\"/></th>".PHP_EOL;
                        $ruleBtn_html.="<tr>".PHP_EOL;

                        $ruleBtn_html.="<tr>".PHP_EOL;
                        $ruleBtn_html.="<th><input type=\"hidden\" name=\"shopid\" value=\"{$shopid}\"/><input type=\"hidden\" name=\"tplid\" value=\"{$tplid}\"/></th>".PHP_EOL;
                        $ruleBtn_html.="<tr>".PHP_EOL;

                        $ruleBtn_html.="<tr>".PHP_EOL;
                        $ruleBtn_html.="<th style='height: 40px;'><input type=\"button\"  value=\"提交\" maxlength=\"30\" size=\"30\" onclick=\"sendForm()\"/></th>".PHP_EOL;
                        $ruleBtn_html.="<tr>".PHP_EOL;

                        $ruleBtn_html.="</table>".PHP_EOL;
                        $ruleBtn_html.="</form>";

                        $format_res = [
                            'ruleBtn_html'=>Theme::encode($ruleBtn_html),
                        ];
                        return_json(0,'操作成功',$format_res);
                    } elseif ($fromtype=='wxapp') {

                        $format_res = [
                            'worktimes_list'=>$worktimes_list_arr,
                            'theme'=>$theme,
                        ];
                        return_json(0,'操作成功',$format_res);

                    }
                }
            }
        }
    }
    //单月日历
    function calendar($year,$month_n,$themeid,$shopid,$birthday){
        global $_P,$_G,$_S,$_C;
        $fromtype = $_P['from'];
        $planedid = $_P['planedid'];//预约的流水id
        
        $date = $year.'-'.$month_n.'-1';   //获取前端传送的时间（时间戳，或者年月）
        $p_year=$year;   //获取前端传值的“年”
        $p_month=$month_n;  //获取前端传值的“月”
        $year_now=date('Y');//获取当前年
        $month=date('m');//获取当年月
        

        //如果前端传值小于等于当前时间(年+月)，从当前月份开始遍历预约时间
        if (strtotime($date) <= time() || ($p_year == $year_now && $p_month == $month)) {
            $j = date("t"); //获取当前月份天数
            // $start_time = time();  //获取今天的时间戳
            $start_time = strtotime(date($year_now.'-'.$month.'-01'));  //获取本月第一天时间戳
            $data = array();
            for($i=0;$i<$j;$i++){
                 $data[] = date('Y-m-d',$start_time+($i)*86400); //本月剩余天，每隔一天赋值给数组
            }
        }
        if ($p_year > $year_now || ($p_year == $year_now && $p_month > $month)){
            $j = date("t",strtotime($date)); //获取当前月份天数
            $start_time = strtotime(date($p_year.'-'.$p_month.'-01'));  //获取本月第一天时间戳
            $data = array();
            for($i=0;$i<$j;$i++){
                 $data[] = date('Y-m-d',$start_time+($i)*86400); //每隔一天赋值给数组
            }
        }
        //$data是需要给前端传值的“日期信息”，需要继续处理，给每一个“日期”加上"已预约数量/总预约数量"

        $storeid = $themeid;
        

        //根据宝宝生日，计算宝宝当前月龄
        if (empty($birthday)) {
            unset($age);
            //return_tips('宝贝生日不能为空！', $url, 'error');
        }else{
            $age = strtotime($birthday); 
            $now = time(); 
            $age=floor(($now-$age)/86400/30);
        }

        //开始获取店铺-分店配置信息
        if ($storeid) {
            $item = ShopplanModel::getConfigByStoreId($storeid);
            $agelimit = $item['agelimit'];//门店年龄限制开关，0为关闭，1为开启
            $end_date = $item['end_date'];//活动的最后1天
            $start_date = $item['start_date'];//活动的开始预约时间
        }

        //查找分店信息
        if (!empty($item['shopconfig'])) {
            $shopconfig=json_decode($item['shopconfig'],TRUE);
            foreach ($shopconfig as $key => $value) {
                if ($shopconfig[$key]['shopid'] == $shopid ) {
                    $shoptime_config['like'] =$value['like'];
                }
            }
        }

        //分店是否与总店使用同样规划规则
        if ($shopid==1 || $shoptime_config['like']==1) {
            $item2 = ShopplanModel::getTimeConfigByStoreId($storeid,'1');
        }else{
            $item2 = ShopplanModel::getTimeConfigByStoreId($storeid,$shopid);
        }


        $id=$item2['id'];//获取分店时间配置表的id

        //获取店铺（storeid或者themeid）的所有规划信息
        $tplitem = ShopplanModel::getSpecialWorktimesListByStoreid($storeid);
        //获取店铺-分店-时间配置信息，结束


        //每周时间规划
        if(!empty($item2['workdays'])){
            $workdays=json_decode($item2['workdays'],TRUE);
        }
        //特殊日期
        if(!empty($item2['special_rules'])){
            $special_rules=json_decode($item2['special_rules'],TRUE);
        }

        //虚拟数据日，虚拟总数
        if (!empty($item2['virtual'])) {
            $virtual01=json_decode($item2['virtual'],TRUE);
            $v_totalnums=$virtual01['virtualnums'];
        }



        $p_data = array();
        //遍历$data，给每个日期：已预约数量/总可预约数量
        if (!empty($data)) {
            foreach ($data as $key => $value) {
                $p_data[$key]['date_end']=intval(substr($value,-2));

                //获取当前日期是周几
                $week=date('w',strtotime($value));

                if ($week==1) {
                    $tplid=$workdays['week01'];
                }elseif ($week==2) {
                    $tplid=$workdays['week02'];
                }elseif ($week==3) {
                    $tplid=$workdays['week03'];
                }elseif ($week==4) {
                    $tplid=$workdays['week04'];
                }elseif ($week==5) {
                    $tplid=$workdays['week05'];
                }elseif ($week==6) {
                    $tplid=$workdays['week06'];
                }elseif ($week==0) {
                    $tplid=$workdays['week07'];
                }


                if ($tplid=='holiday') {
                    $p_data[$key]['totalnums']=0;
                    $p_data[$key]['date']=$value;
                    $p_data[$key]['planed']   =0;
                    $p_data[$key]['tplid']=0;
                }elseif ($tplid=='virtual') {
                    $p_data[$key]['totalnums']=$v_totalnums;
                    $p_data[$key]['date']=$value;
                    $p_data[$key]['planed']   =$v_totalnums;
                    $p_data[$key]['tplid']=0;
                }else{
                    $item3 = ShopplanModel::getSpecialWorktimesById($tplid);
                    $rules3 =json_decode($item3['s_work_rules'],TRUE);
                    $p_data[$key]['totalnums']=0;
                    $p_data[$key]['date']=$value;

                    if ($item3['status']!=1) {
                        $p_data[$key]['totalnums']=0;
                        $p_data[$key]['planed']   =0;
                        $p_data[$key]['tplid']=0;
                    }else{
                        if (!empty($rules3)) {
                            foreach ($rules3 as $k3 => $v3) {
                                if ($agelimit==1 && $v3['ages_start'] <= $age && $age <=$v3['ages_end']) {
                                    $p_data[$key]['totalnums']=$p_data[$key]['totalnums']+$v3['nums'];
                                }elseif($agelimit==1 && empty($v3['ages_end'])) {
                                    $p_data[$key]['totalnums']=$item3['totalnums'];
                                }elseif($agelimit==0) {
                                    $p_data[$key]['totalnums']=$item3['totalnums'];
                                }
                            }
                        }

                        $get_item = ShopplanModel::searchUserPlaned($storeid,$shopid,$value);
                        $p_data[$key]['planed']=isset($get_item[0]['nums'])?$get_item[0]['nums']:0;  
                        $p_data[$key]['tplid']=$tplid;  
                    }
                }

                if(!empty($special_rules)){//规划规则
                    foreach ($special_rules as $k1 => $v1) {
                        if ($value == $v1['workdays']) {
                            $tplid=$v1['tplid'];
                            $item3 = ShopplanModel::getSpecialWorktimesById($tplid);
                            $rules3 =json_decode($item3['s_work_rules'],TRUE);
                            $p_data[$key]['totalnums']=0;
                            $p_data[$key]['date']=$value;
                            //特殊日期赋值特殊计划名称
                            $p_data[$key]['tplname'] = $item3['tplname'];

                            if ($item3['status']!=1) {
                                $p_data[$key]['totalnums']=0;
                                $p_data[$key]['planed']   =0;
                                $p_data[$key]['tplid']=0;
                            }else{

                                if (!empty($rules3)) {
                                    foreach ($rules3 as $k2 => $v2) {
                                        if ($agelimit==1 && $v2['ages_start'] <= $age && $age <=$v2['ages_end']) {
                                            $p_data[$key]['totalnums']=$p_data[$key]['totalnums']+$v2['nums'];
                                        }elseif($agelimit==1 && empty($v2['ages_end'])) {
                                            $p_data[$key]['totalnums']=$item3['totalnums'];
                                        }elseif($agelimit==0){
                                            $p_data[$key]['totalnums']=$item3['totalnums'];
                                        }
                                    }
                                }
                                
                                // $p_data[$key]['totalnums']=$item3['totalnums'];
                                $get_item = ShopplanModel::searchUserPlaned($storeid,$shopid,$value);
                                $p_data[$key]['planed']=isset($get_item[0]['nums'])?$get_item[0]['nums']:0;  
                                $p_data[$key]['tplid']=$tplid;  
                            }
                        }
                    }
                }
                //早于今天的日期，不能预约
//                var_dump(strtotime($value));
//                var_dump(strtotime($start_date));
//                die();
                if (strtotime($value) < strtotime($start_date)) {
                    $p_data[$key]['totalnums']=0;
                    $p_data[$key]['date']=$value;
                    $p_data[$key]['planed']   =0;
                    $p_data[$key]['tplid']=0;
                    $p_data[$key]['is_pre']=1;
                }
                //晚于“活动最后1天”的日期，不可预约
                if (strtotime($value) > strtotime($end_date)) {
                    $p_data[$key]['totalnums']=0;
                    $p_data[$key]['date']=$value;
                    $p_data[$key]['planed']   =0;
                    $p_data[$key]['tplid']=0;
                    $p_data[$key]['is_after']=1;
                }

            }
        }

        //以上部分，直接引入整理好了的$p_data数据

        //获取当前月多少天
        $days=date('t',strtotime("{$year}-{$month_n}-1"));
        //当前一号周几
        $week=date('w',strtotime("{$year}-{$month_n}-1"));
        $day=intval(date('d'));//获取今天是当前月的第几天

        if ($fromtype=='mobile') {

            //拼接输出到前端的日历表
            $ruleBtn_html="<div class=\"swiper-slide\">".PHP_EOL;
            $ruleBtn_html.="<div class=\"dataBar\">".PHP_EOL;
            $ruleBtn_html.="<div class=\"dataTime\"><span>{$month_n}月</span>/{$year}年</div>".PHP_EOL;
            $ruleBtn_html.="<div class=\"dataList\">".PHP_EOL;
            $ruleBtn_html.="<ul>".PHP_EOL;
            if ($days==count($p_data)) {
                for ($i=1-$week; $i <=$days ;) {
                    
                        for ($j=0; $j < 7; $j++) {
                            if ($i>$days || $i<1) {
                                $ruleBtn_html.="<li>&nbsp;</li>".PHP_EOL;
                            }else{
                                if($p_data[$i-1]['planed'] < $p_data[$i-1]['totalnums']){
                                    $ruleBtn_html.="<li class=\"cur\"><a href='/";
                                    $ruleBtn_html.=createMobileUrl("wx",array("planedid"=>$planedid,"themeid"=>$themeid,"shopid"=>$shopid,"birthday"=>$birthday,"date"=>$p_data[$i-1]['date'],"from"=>"mobile","r"=>"shopplan.getweeknav"));
                                    $ruleBtn_html.="'><span>{$i}</span></a>";
                                }elseif ($year==$year_now && $month_n==$month && $day > $i ) {
                                    $ruleBtn_html.="<li><span>{$i}</span>";
                                }elseif($p_data[$i-1]['totalnums'] !=0 && $p_data[$i-1]['planed'] >= $p_data[$i-1]['totalnums']){
                                    $ruleBtn_html.="<li><span>{$i}</span><i>已约满</i>";
                                }elseif($p_data[$i-1]['totalnums'] ==0 && $p_data[$i-1]['tplid'] != 0 && isset($p_data[$i-1]['tplname'])){
                                    $ruleBtn_html.="<li><span>{$i}</span><i style='color:grey;'>{$p_data[$i-1]['tplname']}</i>";
//                                }elseif($p_data[$i-1]['totalnums'] ==0 && $p_data[$i-1]['tplid'] != 0){
//                                    $ruleBtn_html.="<li><span>{$i}</span><i style='color:grey;'>年龄限制</i>";
                                }elseif($p_data[$i-1]['is_after']==1){
                                    $ruleBtn_html.="<li><span>{$i}</span><i style='color:grey;'>不可预约</i>";
                                }elseif($p_data[$i-1]['totalnums']==0){
                                    $ruleBtn_html.="<li><span>{$i}</span><i style='color:grey;'>休息日</i>";
                                }
                                $ruleBtn_html.="</li>".PHP_EOL;
                            }
                            $i++;
                        }
                    
                }
            }
            $ruleBtn_html.="</ul>".PHP_EOL;
            $ruleBtn_html.="</div>".PHP_EOL;
            $ruleBtn_html.="</div>".PHP_EOL;
            $ruleBtn_html.="</div>".PHP_EOL;

            return $ruleBtn_html;
            /*
            $format_res = [
                // 'ruleBtn_html'=>Theme::encode($ruleBtn_html),
                'ruleBtn_html'=>$ruleBtn_html,
            ];
            return_json(0,'操作成功',$format_res);
            */
    
        } elseif ($fromtype=='wxapp') {

            $format_res = [
                'days'=>$p_data,
                'week'=>$week,
                'year'=>$year,
                'month'=>intval($month_n)
            ];
            return $format_res;
            // return_json(0,'操作成功',$format_res);
        }
    }
    //请求三个月的（h5
    function getmonths(){
        global $_P,$_G,$_S,$_C;
        $fromtype = $_P['from'];
        $themeid = $_P['themeid'];//获取themeid，或者说店铺id
        $shopid = isset($_P['shopid'])?$_P['shopid']:'1';  //获取分店shopid
        $birthday = $_P['birthday'];  //获取宝贝生日
        $times = $_P['times'];//获取第几次触底请求
        $planedid = $_P['planedid'];//预约的流水id  
        $storeid = $_P['storeid']?$_P['storeid']:$themeid;

        //开始获取店铺-分店配置信息
        if ($storeid) {
            $item = ShopplanModel::getConfigByStoreId($storeid);
            $end_date = $item['end_date'];//活动的最后1天 
            $year_end =date('Y',strtotime($end_date));//获取活动结束年
            $month_end=date('m',strtotime($end_date));//获取活动结束月
        }

        $year=date('Y');//获取当前年
        $month=date('m');//获取当年月

        if (isset($times)) {
            $year = intval($year) + intval(($month + ($times+1)*3)/12);
            $month =($month + ($times+1)*3)%12;
        }
        // if ($year < $year_end || ($year == $year_end && $month <= $month_end)) {
            $month1 = $this-> calendar($year,$month,$themeid,$shopid,$birthday);
            //计算下个月
            if($month==12){
                $year=$year+1;
                $month=1;
            }else{
                $year=$year;
                $month=$month+1;
            }
        // }
        // if ($year < $year_end || ($year == $year_end && $month <= $month_end)) {
            $month2 = $this-> calendar($year,$month,$themeid,$shopid,$birthday);
            //计算下个月
            if($month==12){
                $year=$year+1;
                $month=1;
            }else{
                $year=$year;
                $month=$month+1;
            }
        // }
        // if ($year < $year_end || ($year == $year_end && $month <= $month_end)) {
            $month3 = $this-> calendar($year,$month,$themeid,$shopid,$birthday);
        // }
        
        $month =$month1.$month2.$month3;

        $format_res = [
            // 'ruleBtn_html'=>Theme::encode($ruleBtn_html),
            'ruleBtn_html'=>$month,
        ];

        return_json(0,'操作成功',$format_res);
    }
    //客户预约表（入库）
    function userplaned(){
        global $_P,$_G,$_S,$_C;
        $fromtype = $_P['from'];

        if (!$_G['ispost']) {
            return_json(1,'发生了意外');
        } else {
            $themeid = isset($_P['themeid'])?$_P['themeid']:'';
            $theme = Theme::getThemeById($themeid);
            $fromuid = isset($_P['fromuid'])?$_P['fromuid']:'';

            if (!$themeid || !$theme) {
                return_json(1,'活动入口不正确');
            } else {
                $fans = $this->checkuser();
                if ($fans && $fans['uid']){

                    //接受并处理前端传值信息
                    $shopid = isset($_P['shopid'])?$_P['shopid']:'1';
                    $storeid = isset($_P['themeid'])?$_P['themeid']:$_P['storeid'];
                    $birthday = $_P['birthday'];
                    $note = trim($_P['note']);
                    $date = $_P['date'];   //获取前端传送的日期（年+月+日）
                    $time = $_P['time'];   //获取前端传送的时间（hh:ii）
                    $tplid= $_P['tplid'];

                    // $planedinfo = ShopplanModel::getUserPlanByUid($fans['uid'],$themeid);

                    // if ($planedinfo) {
                    //     return_json(1,'您已经预约过了！');
                    // }
                    
                    //开始获取店铺-分店配置信息
                    if ($storeid) {
                        $item = ShopplanModel::getConfigByStoreId($storeid);
                        $agelimit = $item['agelimit'];//门店年龄限制开关，0为关闭，1为开启
                    }

                    if (empty($fans['uid'])) {
                        return_json(1,'用户uid不能为空！');
                    }
                    if (empty($date)) {
                        return_json(1,'预约日期不能为空！');
                    }
                    if (empty($time)) {
                        return_json(1,'预约时间段不能为空！');
                    }
                    if (empty($birthday) && $agelimit ==1) {
                        return_json(1,'宝贝生日不能为空！');
                    }

                    //根据宝宝生日，计算宝宝当前月龄
                    $age = strtotime($birthday); 
                    $now = strtotime("now"); 
                    $age=floor(($now-$age)/86400/30);

                    //如果有（商家id+店铺id），获取配置信息
                    if ($storeid && $shopid >= 1) {
                        $item2 = ShopplanModel::getTimeConfigByStoreId($storeid,$shopid);
                    }

                    //规划规则
                    $item3 = ShopplanModel::getSpecialWorktimesById($tplid);
                    $work_rules=json_decode($item3['s_work_rules'],TRUE);


                    //获取已经预约的（时间段+数量）
                    $get_item = ShopplanModel::searchUserPlaned4($themeid,$shopid,$date);
                    sort($get_item);
                    if (!empty($work_rules)) {
                        foreach ($work_rules as $k => $v) {
                            foreach ($get_item as $key1 => $value1) {
                                if ($v['worktimes']==substr($value1['p_date'],-5)) {
                                    if ($work_rules[$k]['nums']>=$value1['nums']) {
                                        $work_rules[$k]['p_nums']=$value1['nums'];
                                    }else{
                                        return_json(1,'本时间段预约人数超标！');//报错，提示本时间段预约满员
                                    }
                                }
                            }
                            //预约年龄区间处理
                            if($item3['agelimit'==1]){
                                if ($v['ages_start'] > $age) {
                                    return_json(1,'本时间段预约，您的宝贝年龄过小！');
                                }elseif ($age > $v['ages_end']) {
                                    return_json(1,'本时间段预约，您的宝贝年龄偏大！');
                                }
                            }
                        }
                    }

                    //前端可以使用$work_rules数据


                    $date=date('Y-m-d',strtotime($date));   //获取前端传值的“年”
                    $plan_at= $date.' '.$time.':00';

                    $id  = $_P['planedid'];//获取用户预约保存的id

                    //整理之后入库
                    if (!$id || $id == 'undefined'){
                        $item2 = ShopplanModel::getConfigByStoreId($themeid);

                        //如果没有分店名称，查找分店名称
                        $shopconfig=json_decode($item2['shopconfig'],TRUE);
                        if (!empty($shopconfig)) {
                            foreach ($shopconfig as $key => $value) {
                                if ($shopconfig[$key]['shopid'] == $shopid) {
                                    $old_shopname =$value['name'];
                                }
                            }
                        }

                        $info = '客户'.$fans['username'].',于'.date("Y-m-d H:i").',预约"'.$old_shopname.','.$plan_at.'"';
                        $log[]=$info;
                        $data = [
                            'uid'           =>$fans['uid'],                       //用户id
                            'storeid'       =>$themeid,                           //商家id(活动的themeid)
                            'shopid'        =>$shopid,                            //分店id
                            'plan_at'       =>$plan_at,                           //客户预约（日期+时间）
                            'birthday'      =>date("Y-m-d",strtotime($birthday)), //宝贝生日
                            'created_at'    =>date("Y-m-d H:i:s"),         //预约的创建时间
                            'note'          =>$note,                              //客户留言备注
                            'log'           =>json_encode($log),                  //客户存储日志
                            'updated_at'    =>date("Y-m-d H:i:s"),         //更新时间
                        ];

                        $res = ShopplanModel::insertUserPlan($data);

                        $id = $planedid =$res;

                    }else{
                        $where = ['id'=>$id];
                        $planedinfo = ShopplanModel::getUserPlanById($id);
                        if (!empty($planedinfo['log'])) {
                            $log = json_decode($planedinfo['log'],TRUE);
                        }

                        $item2 = ShopplanModel::getConfigByStoreId($planedinfo['storeid']);

                        //如果没有分店名称，查找分店名称
                        $shopconfig=json_decode($item2['shopconfig'],TRUE);
                        if (!empty($shopconfig)) {
                            foreach ($shopconfig as $key => $value) {
                                if ($shopconfig[$key]['shopid'] == $planedinfo['shopid']) {
                                    $old_shopname =$value['name'];
                                }
                                if ($shopconfig[$key]['shopid'] ==$shopid) {
                                    $new_shopname =$value['name'];
                                }
                            }
                        }

                        $user['name']=$fans['username'];//用户名
                        //客户自己修改的日志
                        //客户“***”，某日期，第几次修改，把原信息“门店，预约时间”，修改为“门店，预约时间”
                        $info = '客户'.$fans['username'].',于'.date("Y-m-d H:i").',第'.($planedinfo['edit_nums']+1).'次修改，把原预约信息"'.$old_shopname.','.$planedinfo['plan_at'].'",修改为："'.$new_shopname.','.$plan_at.'"';

                        $log[]=$info;
                       
                        //数据库增加1个字段，把上述信息写入，分条写入

                        $data = [
                            'shopid'        =>$shopid,                            //分店id
                            'plan_at'       =>$plan_at,                           //客户预约（日期+时间）
                            'birthday'      =>date("Y-m-d",strtotime($birthday)), //宝贝生日
                            'note'          =>$note,                              //客户留言备注
                            'edit_nums'     =>($planedinfo['edit_nums']+1),       //客户已经自助修改次数
                            'log'           =>json_encode($log),                  //客户修改日志
                            'updated_at'    =>date("Y-m-d H:i:s"),         //更新时间
                        ];

                        $res = ShopplanModel::editUserPlanByWhere($where,$data);
                    }

                    if (!$res){
                        return_json(1,'操作失败');
                    }else{
                        $ruleBtn_html='您已经成功预约！预约时间是：'.$plan_at;
                        if ($fromtype=='mobile') {
                            $format_res = [
                                'ruleBtn_html'=>$ruleBtn_html,
                            ];
                        }elseif ($fromtype=='wxapp'){
                            $format_res = [
                                'ruleBtn_html'=>$ruleBtn_html,
                            ];
                        }
                        return_json(0,'操作成功',$format_res);
                    }


                }
                return_json(1,'操作失败-没有登陆');
            }
        }
    }
    //请求1周
    function weeknav($themeid,$shopid,$date,$birthday){
        global $_P,$_G,$_S,$_C;
        $fromtype = $_P['from'];
        $planedid = $_P['planedid'];//预约的流水id 
        $storeid = isset($_P['storeid'])?$_P['storeid']:$themeid;
        //开始获取店铺-分店配置信息
        if ($storeid) {
            $item = ShopplanModel::getConfigByStoreId($storeid);
            $agelimit = $item['agelimit'];//门店年龄限制开关，0为关闭，1为开启
            $end_date = $item['end_date'];//活动的最后1天
            $start_date = $item['start_date'];//活动的开始预约时间
        }

        //获取当前的1周日期
        $date = $_P['date'];
        $add = $_P['add'];
        if(empty($date)){
            $start_time = time();  //获取今天的时间戳
        }elseif ((strtotime($date)+3*86400) >= strtotime($end_date)) {
            $start_time = strtotime($end_date)-(86400*6);
        }else{
            $start_time = strtotime($date) - (86400*3);
        }

        if($start_time <= time()){
            $start_time = time();
        }

        $data = array();
        for($i=0;$i<7;$i++){
            //日期取值，不能晚于“活动最后1天”
            if ($start_time+($i)*86400 <= strtotime($end_date)) {
                $data[$i] = date('Y-m-d',$start_time+($i)*86400); //剩余天，每隔一天赋值给数组
            }
        }

        //$data是需要给前端传值的“日期信息”，需要继续处理，给每一个“日期”加上"已预约数量/总预约数量"

        

        //根据宝宝生日，计算宝宝当前月龄
        if (empty($birthday)) {
            unset($age);
            //return_tips('宝贝生日不能为空！', $url, 'error');
        }else{
            $age = strtotime($birthday);
            $now = time();
            $age=floor(($now-$age)/86400/30);
        }




        //查找分店信息
        if (!empty($item['shopconfig'])) {
            $shopconfig=json_decode($item['shopconfig'],TRUE);
            foreach ($shopconfig as $key => $value) {
                if ($shopconfig[$key]['shopid'] == $shopid ) {
                    $shoptime_config['like'] =$value['like'];
                    $shop['name']=$value['name'];
                    $shop['address']=$value['address'];
                    $shop['phone']=$value['phone'];
                }
            }
        }

        //分店是否与总店使用同样规划规则
        if ($shopid==1 || $shoptime_config['like']==1) {
            $item2 = ShopplanModel::getTimeConfigByStoreId($storeid,'1');
        }else{
            $item2 = ShopplanModel::getTimeConfigByStoreId($storeid,$shopid);
        }



        $id=$item2['id'];//获取分店时间配置表的id


        //获取店铺（storeid或者themeid）的所有规划信息
        $tplitem = ShopplanModel::getSpecialWorktimesListByStoreid($storeid);
        //获取店铺-分店-时间配置信息，结束


        //每周时间规划
        if(!empty($item2['workdays'])){
            $workdays=json_decode($item2['workdays'],TRUE);
        }
        //特殊日期
        if(!empty($item2['special_rules'])){
            $special_rules=json_decode($item2['special_rules'],TRUE);
        }

        //虚拟数据日，虚拟总数
        if (!empty($item2['virtual'])) {
            $virtual01=json_decode($item2['virtual'],TRUE);
            $v_totalnums=$virtual01['virtualnums'];
        }


        $p_data = array();
        //遍历$data，给每个日期：已预约数量/总可预约数量，获取可预约的时间段
        if (!empty($data)) {
            foreach ($data as $key => $value) {
                //获取当前日期是周几
                $week=date('w',strtotime($value));

                if ($week==1) {
                    $tplid=$workdays['week01'];
                    $weeknav='周一';
                }elseif ($week==2) {
                    $tplid=$workdays['week02'];
                    $weeknav='周二';
                }elseif ($week==3) {
                    $tplid=$workdays['week03'];
                    $weeknav='周三';
                }elseif ($week==4) {
                    $tplid=$workdays['week04'];
                    $weeknav='周四';
                }elseif ($week==5) {
                    $tplid=$workdays['week05'];
                    $weeknav='周五';
                }elseif ($week==6) {
                    $tplid=$workdays['week06'];
                    $weeknav='周六';
                }elseif ($week==0) {
                    $tplid=$workdays['week07'];
                    $weeknav='周日';
                }

                $p_data[$key]['date']=$value;
                $p_data[$key]['week']=$weeknav;
                $p_data[$key]['worktimes']=0;


                if ($tplid=='holiday') {
                    $p_data[$key]['totalnums']=0;
                    $p_data[$key]['planed']   =0;
                    $p_data[$key]['tplid']=0;
                }elseif ($tplid=='virtual') {
                    $p_data[$key]['totalnums']=$v_totalnums;
                    $p_data[$key]['planed']   =$v_totalnums;
                    $p_data[$key]['tplid']=0;
                }else{
                    $item3 = ShopplanModel::getSpecialWorktimesById($tplid);
                    $rules3 =json_decode($item3['s_work_rules'],TRUE);
                    $p_data[$key]['totalnums']=0;



                    if ($item3['status']!=1) {
                        $p_data[$key]['totalnums']=0;
                        $p_data[$key]['planed']   =0;
                        $p_data[$key]['tplid']=0;
                    }else{
                        if (!empty($rules3)) {
                            foreach ($rules3 as $k3 => $v3) {
                                //有年龄限制，年龄在“起止日期之间”，累积totalnums数量
                                if ($agelimit==1 && $v3['ages_start'] <= $age && $age <=$v3['ages_end']) {
                                    $p_data[$key]['totalnums']=$p_data[$key]['totalnums']+$v3['nums'];
                                }elseif($agelimit == 1 && empty($v3['ages_end'])){//有年龄限制，但截止月龄为0、为空的，累积totalnums数量
                                    $p_data[$key]['totalnums']=$p_data[$key]['totalnums']+$v3['nums'];
                                }elseif($agelimit == 0){
                                    $p_data[$key]['totalnums']=$item3['totalnums'];
                                }
                            }
                        }

                        $get_item = ShopplanModel::searchUserPlaned($storeid,$shopid,$value);

                        $p_data[$key]['planed']=isset($get_item[0]['nums'])?$get_item[0]['nums']:0;
                        $p_data[$key]['tplid']=$tplid;

                        //获取已经预约的（时间段+数量）
                        $get_item2 = ShopplanModel::searchUserPlaned4($storeid,$shopid,$value);
                        sort($get_item2);
                        $p_data[$key]['worktimes']=[];
                        foreach ($rules3 as $k => $v) {

                            $v['p_nums']=!empty($v['p_nums'])?$v['p_nums']:'0';
                            foreach ($get_item2 as  $value1) {
                                if ($v['worktimes']==substr($value1['p_date'],-5)) {
                                    $v['p_nums']=$rules3[$k]['p_nums']=$value1['nums'];
                                }
                            }
                            //获取规划中的所有时间段
                            $p_data[$key]['worktimes'][$k]=$v['worktimes'];
                            //获取与时间段$p_data[$key]['worktimes'][$k]，相对应的$p_data[$key]['can_plan'][$k]，用来判断每个时间段【$k】是否可以预约
                            if($agelimit==1 && $v['p_nums'] < $v['nums'] && $v['ages_start'] <= $age && $age <= $v['ages_end']){
                                $p_data[$key]['can_plan'][$k] = 1;
                            }elseif($agelimit==1 && $v['p_nums'] < $v['nums'] && empty($v['ages_end'])){
                                $p_data[$key]['can_plan'][$k] = 1;
                            }elseif($agelimit==0 && $v['p_nums'] < $v['nums']){
                                $p_data[$key]['can_plan'][$k] = 1;
                            }else{
                                $p_data[$key]['can_plan'][$k] = 0;
                            }

                            //如果是今天，时间段小于当前时间戳的，去除
                            /*
                            $arr=[];
                            if ($value==date("Y-m-d")){
                                $time=$value.' '.$v['worktimes'].':00';
                                if (strtotime($time) - time() <= 0){
                                    array_push($arr,$v['worktimes']);
                                    $p_data[$key]['worktimes'] = array_merge(array_diff($p_data[$key]['worktimes'], $arr));

                                }
                            }*/
                        }
                    }
                }

                if(!empty($special_rules)){//规划规则
                    foreach ($special_rules as $k1 => $v1) {
                        if ($value == $v1['workdays']) {
                            $tplid=$v1['tplid'];
                            $item3 = ShopplanModel::getSpecialWorktimesById($tplid);
                            $rules3 =json_decode($item3['s_work_rules'],TRUE);
                            $p_data[$key]['totalnums']=0;

                            if ($item3['status']!=1) {
                                $p_data[$key]['totalnums']=0;
                                $p_data[$key]['planed']   =0;
                                $p_data[$key]['tplid']=0;
                            }else{

                                if (!empty($rules3)) {
                                    foreach ($rules3 as $k2 => $v2) {
                                        //有年龄限制，年龄在“起止日期之间”，累积totalnums数量
                                        if ($agelimit==1 && $v2['ages_start'] <= $age && $age <=$v2['ages_end']) {
                                            $p_data[$key]['totalnums']=$p_data[$key]['totalnums']+$v2['nums'];
                                        }elseif($agelimit == 1 && empty($v2['ages_end'])){//有年龄限制，但截止月龄为0、为空的，累积totalnums数量
                                            $p_data[$key]['totalnums']=$p_data[$key]['totalnums']+$v2['nums'];
                                        }elseif($agelimit == 0){
                                            $p_data[$key]['totalnums']=$item3['totalnums'];
                                        }
                                    }
                                }


                                // $p_data[$key]['totalnums']=$item3['totalnums'];
                                $get_item = ShopplanModel::searchUserPlaned($storeid,$shopid,$value);
                                $p_data[$key]['planed']=isset($get_item[0]['nums'])?$get_item[0]['nums']:0;
                                $p_data[$key]['tplid']=$tplid;

                                //获取已经预约的（时间段+数量）
                                $get_item2 = ShopplanModel::searchUserPlaned4($storeid,$shopid,$value);
                                sort($get_item2);

                                $p_data[$key]['worktimes']=[];
                                foreach ($rules3 as $k => $v) {
                                    $v['p_nums']=!empty($v['p_nums'])?$v['p_nums']:'0';
                                    foreach ($get_item2 as  $value1) {
                                        if ($v['worktimes']==substr($value1['p_date'],-5)) {
                                            $rules3[$k]['p_nums']=$value1['nums'];
                                        }
                                    }

                                    //获取规划中的所有时间段
                                    $p_data[$key]['worktimes'][$k]=$v['worktimes'];

                                    //获取与时间段$p_data[$key]['worktimes'][$k]，相对应的$p_data[$key]['can_plan'][$k]，用来判断每个时间段【$k】是否可以预约
                                    if($agelimit==1 && $v['p_nums'] < $v['nums'] && $v['ages_start'] <= $age && $age <= $v['ages_end']){
                                        $p_data[$key]['can_plan'][$k] = 1;
                                    }elseif($agelimit==1 &&$v['p_nums'] < $v['nums'] && empty($v['ages_end'])){
                                        $p_data[$key]['can_plan'][$k] = 1;
                                    }elseif($agelimit==0 &&$v['p_nums'] < $v['nums']){
                                        $p_data[$key]['can_plan'][$k] = 1;
                                    }else{
                                        $p_data[$key]['can_plan'][$k] = 0;
                                    }

                                    //如果是今天，时间段小于当前时间戳的，去除
                                    /*
                                    $arr=[];
                                    if ($value==date("Y-m-d")){
                                        $time=$value.' '.$v['worktimes'].':00';
                                        if (strtotime($time) - time() <= 0){
                                            array_push($arr,$v['worktimes']);
                                            $p_data[$key]['worktimes'] = array_merge(array_diff($p_data[$key]['worktimes'], $arr));

                                        }
                                    }*/

                                }
                            }
                        }
                    }
                }
                //处理时间段，分为：上午组+下午组
                if( empty($p_data[$key]['worktimes']) ){
                    $p_data[$key]['worktimes'] = 0;
                }
                else{
                    foreach ($p_data[$key]['worktimes'] as $times_k => $times_v) {
                        $hours  =  intval(substr($times_v,0,2));
                        $minutes=  intval(substr($times_v,-2));
                        if ($hours < 12 ) {
                            $p_data[$key]['am'][] =$times_v;
                            $p_data[$key]['am_can_plan'][] =$p_data[$key]['can_plan'][$times_k];
                        }elseif ($hours == 12 && $minutes == 0) {
                            $p_data[$key]['am'][] =$times_v;
                            $p_data[$key]['am_can_plan'][] =$p_data[$key]['can_plan'][$times_k];
                        }elseif ($hours == 12 && $minutes > 0) {
                            $p_data[$key]['pm'][] =$times_v;
                            $p_data[$key]['pm_can_plan'][] =$p_data[$key]['can_plan'][$times_k];
                        }elseif ($hours > 12) {
                            $p_data[$key]['pm'][] =$times_v;
                            $p_data[$key]['pm_can_plan'][] =$p_data[$key]['can_plan'][$times_k];
                        }
                    }
                }
            }
        }
        if (!empty($p_data)){
            foreach ($p_data as $key =>$val)
            {
                if ((strtotime($val['date'])<strtotime($start_date)) || (strtotime($val['date']) > strtotime($end_date))){
                    $p_data[$key]['planed'] = 0;
                    $p_data[$key]['totalnums'] = 0;
                    $p_data[$key]['tplid'] = 0;
                    $p_data[$key]['worktimes'] = 0;
                    unset($p_data[$key]['am']);
                    unset($p_data[$key]['am_can_plan']);
                    unset($p_data[$key]['can_plan']);
                    unset($p_data[$key]['pm']);
                    unset($p_data[$key]['pm_can_plan']);
                }
            }
        }

        //以上部分，直接引入整理好了的$p_data数据

        $format_res = [
            'days'=>$p_data,
            'shop'=>$shop,
        ];
        return $format_res;
    }
    //查询店名或地址(小程序
    function searchshop(){
        global $_P,$_G,$_S,$_C;
        $fromtype = $_P['from'];
        //基本检测
        $fans = $this->checkuser();
        $themeid = isset($_P['themeid'])?$_P['themeid']:'';
        $theme = Theme::getThemeById($themeid);
        $fromuid = isset($_P['fromuid'])?$_P['fromuid']:'';

        if (!$themeid || !$theme) {
            return_json(1,'活动入口不正确');
        }
        //获取搜索框的内容
        $search_data = isset($_P['search_data'])?$_P['search_data']:'';

        $storeid = $_P['storeid']?$_P['storeid']:$themeid;

        //开始获取店铺-分店配置信息
        if ($storeid) {
            $item = ShopplanModel::getConfigByStoreId($storeid);
        }

        //如果搜索框内容为空，展示全部店铺
        if (!empty($item['shopconfig'])) {
            $shopconfig=json_decode($item['shopconfig'],TRUE);

            if(empty($search_data)){
                $temp2 = $shopconfig;
            }else{
                //查找分店信息
                $temp_shopconfig=[];
                foreach ($shopconfig as $key => $value) {
                    //防止重复shopid
                    if (strstr($value['name'],$search_data)){
                        array_push($temp_shopconfig,$value);
                    }elseif (strstr($value['address'],$search_data)){
                        array_push($temp_shopconfig,$value);
                    }
                }


                foreach ($temp_shopconfig as $k=>$v){
                    $v = join(",",$v);  //降维,也可以用implode,将一维数组转换为用逗号连接的字符串
                    $temp[$k] = $v;
                }
                if (!empty($temp)) {
                    $temp = array_unique($temp);    //去掉重复的字符串,也就是重复的一维数组
                    foreach ($temp as $k => $v){
                        $array=explode(",",$v);     //再将拆开的数组重新组装
                        $temp2[$k]["name"] =$array[0];  
                        $temp2[$k]["address"] =$array[1];
                        $temp2[$k]["phone"] =$array[2];
                        $temp2[$k]["like"] =$array[3];
                        $temp2[$k]["shopid"] =$array[4];
                        $temp2[$k]["logo"] =$array[5];
                    }
                }
            }
        }

        $format_res = [
            'shopconfig'=>$temp2,
        ];
        return_json(0,'操作成功',$format_res);
    }
    //获取店铺列表（h5
    function getshops(){
        global $_P,$_G,$_S,$_C;
        $fromtype = $_P['from'];
        //基本检测
        $fans = $this->checkuser();
        $user['name']=$fans['username'];//用户名
        $user['mobile']=$fans['mobile'];//用户手机

        $themeid = isset($_P['themeid'])?$_P['themeid']:'';
        $theme = Theme::getThemeById($themeid);
        $fromuid = isset($_P['fromuid'])?$_P['fromuid']:'';

        if (!$themeid || !$theme) {
            return_json(1,'活动入口不正确');
        }

        $date = $_P['date'];//选中的预约“日期”
        $birthday = $_P['birthday'];//宝贝生日
        
        //检查该活动id（店铺id），该用户uid时候有过预约
        $planedinfo = ShopplanModel::getUserPlanByUid($fans['uid'],$themeid);
        $planedid = $_P['planedid'];//预约的流水id
        if(isset($planedid)){
            $planedinfo = false;
        }

        //预约过的客户，返回原来的预约信息
        if ($planedinfo) {
            $storeid = $planedinfo['storeid'];
            $shopid  = $planedinfo['shopid'];

            //开始获取店铺-分店配置信息
            if ($storeid) {
                $item = ShopplanModel::getConfigByStoreId($storeid);
                $agelimit = $item['agelimit'];//门店年龄限制开关，0为关闭，1为开启
            }
            //查找分店信息
            if (!empty($item['shopconfig'])) {
                $shopconfig=json_decode($item['shopconfig'],TRUE);
                foreach ($shopconfig as $key => $value) {
                    if ($value['shopid'] ==$shopid) {
                        $shop['name'] = $value['name'];
                        $shop['address']  = $value['address'];
                        $shop['phone']  = $value['phone'];
                    }
                }
            }

            $planedinfo['plan_at']=substr($planedinfo['plan_at'],0,-3);
            $date=substr($planedinfo['plan_at'],0,-6);  //注意：是在上一行截取了-3的基础上，又截取了-6
            
            if ($planedinfo['birthday']=='0000-00-00 00:00:00') {
                $birthday = '';
            } else {
                $birthday = date('Y-m-d',strtotime($planedinfo['birthday']));
            }
            

            $planedid = $planedinfo['id'];

            //获取条件，判断是否可以客户自助修改
            //条件1：预约之后,最长多少天内可以修改,默认7天，$item['enable_days']
            //条件2：距离预约的日期,最晚多少天之外可以修改,默认3天，$item['days_away']
            //条件3：客户最多可修改的次数,默认5次，$item['max_edit_nums']

            $self_edit = false;
            if ((strtotime($planedinfo['created_at'])+$item['enable_days']*86400 >= time()) && (strtotime($planedinfo['plan_at'])-$item['days_away']*86400 >= time()) && $planedinfo['edit_nums'] < $item['max_edit_nums']) {
                $self_edit = true;
            }

            $return_client = get_defined_vars();
        return $this->view("shopplan/success", $return_client);

        }else{

            $storeid = $_P['storeid']?$_P['storeid']:$themeid;
            //开始获取店铺-分店配置信息
            if ($storeid) {
                $item = ShopplanModel::getConfigByStoreId($storeid);
                $agelimit = $item['agelimit'];//门店年龄限制开关，0为关闭，1为开启
            }
            //获取搜索框的内容
            $search_data = isset($_P['search_data'])?$_P['search_data']:'';
            //如果搜索框内容为空，展示全部店铺
            $defaultShopId = 0;
            if (!empty($item['shopconfig'])) {
                $shopconfig=json_decode($item['shopconfig'],TRUE);

                if(empty($search_data)){
                    $shopconfig = $shopconfig;
                }else{
                    //查找分店信息
                    $temp_shopconfig=[];
                    foreach ($shopconfig as $key => $value) {

                        if (strstr($value['name'],$search_data)){
                            array_push($temp_shopconfig,$value);
                        }elseif (strstr($value['address'],$search_data)){
                            array_push($temp_shopconfig,$value);
                        }
                    }
                    //防止重复shopid
                    foreach ($temp_shopconfig as $k=>$v){
                        $v = join(",",$v);  //降维,也可以用implode,将一维数组转换为用逗号连接的字符串
                        $temp[$k] = $v;
                    }
                    if (!empty($temp)) {
                        $temp = array_unique($temp);    //去掉重复的字符串,也就是重复的一维数组
                        foreach ($temp as $k => $v){
                            $array=explode(",",$v);     //再将拆开的数组重新组装
                            $temp2[$k]["name"] =$array[0];
                            $temp2[$k]["address"] =$array[1];
                            $temp2[$k]["phone"] =$array[2];
                            $temp2[$k]["like"] =$array[3];
                            $temp2[$k]["shopid"] =$array[4];
                            $temp2[$k]["logo"] =$array[5];
                        }
                    }
                    $shopconfig=$temp2;
                }
                $shoplength=count($shopconfig);
                if($shoplength == 1) $defaultShopId = $shopconfig[0]['shopid'];
            }
            $return_client = get_defined_vars();
        return $this->view("shopplan/shoper", $return_client);
        }

    }
    //获取日历选择界面(h5+小程序
    function getcalendar(){
        global $_P,$_G,$_S,$_C;
        $fromtype = $_P['from'];

        $themeid = $_P['themeid'];//获取themeid，或者说店铺id
        $theme = Theme::getThemeById($themeid);
        $storeid = $_P['storeid']?$_P['storeid']:$themeid;
        $shopid = isset($_P['shopid'])?$_P['shopid']:'1';  //获取分店shopid
        $birthday = $_P['birthday'];  //获取宝贝生日
        $planedid = $_P['planedid'];//预约的流水id   

        $add = $_P['add'];

        if ($add=='scrolltolower') {
            $year = $_P['year'];
            $month = $_P['month'];
            //计算开始追加的月
            if($month==12){
                $year=$year+1;
                $month=1;
            }else{
                $year=$year;
                $month=$month+1;
            }
        } else{
            $year=date('Y');//获取当前年
            $month=date('m');//获取当年月
        }

        //开始获取店铺-分店-配置信息
        if ($storeid) {
            $item = ShopplanModel::getConfigByStoreId($storeid);
            $end_date = $item['end_date'];//活动的最后1天 
            $year_end =date('Y',strtotime($end_date));//获取活动结束年
            $month_end=date('m',strtotime($end_date));//获取活动结束月
        }

        if ($fromtype=='wxapp') {

           // $monthnums = 3;//小程序端，获取3个月
            $date1 = explode('-',date('Y-m'));
            $date2 = explode('-',$year_end.'-'.$month_end);
            $monthnums = abs( ($date2[0] - $date1[0]) * 12 + $date2[1] - $date1[1]);
            for ($i=0; $i <= $monthnums; $i++) {
                //日期晚于“活动最后1天”的活动年、活动月，不能预约
                // if ($year < $year_end || ($year == $year_end && $month <= $month_end)) {
                    $month_res[$i]= $this->calendar($year,$month,$themeid,$shopid,$birthday);

                    //计算下个月
                    if($month==12){
                        $year=$year+1;
                        $month=1;
                    }else{
                        $year=$year;
                        $month=$month+1;
                    }
                // }
            }
            $format_res['theme'] = $theme;
            $format_res['data'] = $month_res;
            return_json(0,'操作成功',$format_res);
        }
        $return_client = get_defined_vars();
        return $this->view("shopplan/data", $return_client);
    }
    //获取1周界面(h5+小程序
    function getweeknav(){
        global $_P,$_G,$_S,$_C;
        $fromtype = $_P['from'];

        $themeid = $_P['themeid'];//获取themeid，或者说店铺id
        $theme = Theme::getThemeById($themeid);
        $storeid = $_P['storeid']?$_P['storeid']:$themeid;
        $shopid = isset($_P['shopid'])?$_P['shopid']:'1';  //获取分店shopid
        $date = $_P['date'];//预约的日期
        $birthday = $_P['birthday'];  //获取宝贝生日
        $planedid = $_P['planedid'];//预约的流水id  

        $datenow = date('Y-m-d');//当前日期

        //开始获取店铺-分店配置信息
        if ($storeid) {
            $item = ShopplanModel::getConfigByStoreId($storeid);
            $shopconfig=json_decode($item['shopconfig'],TRUE);
            $shoplength=count($shopconfig);
            $end_date = $item['end_date'];//活动的最后1天 
        }


        $start_time = strtotime($date); ;

        if(($start_time-time()) >= (86400*3)){
            if ($start_time-strtotime($end_date) >= 0) {
                $t=6;
            }elseif ((strtotime($end_date)-$start_time)/86400 <= 3) {
                $t=6-ceil((strtotime($end_date)-$start_time)/86400);
            }else{
                $t=3;
            }
        } else{
            $t=ceil(($start_time-time())/86400);
        }

        $data = $this ->weeknav($themeid,$shopid,$date,$birthday);

        if ($fromtype=='wxapp') {

            $format_res = [
                'ruleBtn_html'=>$data,
                'indext'=>$t,
                'shoplength'=>$shoplength,
                'theme'=>$theme,
            ];

            return_json(0,'操作成功',$format_res);

        }

        $return_client = get_defined_vars();
        return $this->view("shopplan/weeknav", $return_client);
    }

}